﻿using BusinessLayer;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BusinessLayer.BLServerReference;

namespace WebFrontEnd
{
    public partial class Login : System.Web.UI.Page
    {
        #region Private Memebers
        private IBL _bl;
        #endregion

        #region Constructor
        public Login()
        {
            _bl = BusinessLayerFactory.GetCurrentBusinessLayer(ConfigurationManager.AppSettings.Get("DomainName"));
        }
        #endregion

        #region Page Handlers
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.User.Identity.IsAuthenticated)
            {
                Response.Redirect("Default.aspx");
            }
            if (Session["flash"] != null)
            {
                flashmessage.InnerHtml = (string)Session["flash"];
                Session.Remove("flash");
            }
        }
        #endregion

        #region Event Handlers
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            var report = _bl.LoginUser(username.Text, password.Text);
            if (!report.Valid)
            {
                TurnOnError(report.Message,loginerroralert,loginAlertText);
                LoginTab.Attributes["class"] = "active";
                CreateTab.Attributes["class"] = "";
                CreateTabPane.Attributes["class"] = CreateTabPane.Attributes["class"].Replace("active", "");

                if (!LoginTabPane.Attributes["class"].Contains("active"))
                {
                    LoginTabPane.Attributes["class"] = LoginTabPane.Attributes["class"].Replace("fade", "") + " active in";
                }
            }
            else
            {
                FormsAuthentication.RedirectFromLoginPage(report.ModelObject.Email, RememberMeCheckbox.Checked);
            }
        }

        protected void CreateButton_Click(object sender, EventArgs e)
        {
            LoginTab.Attributes["class"] = "";
            CreateTab.Attributes["class"] = "active";
            LoginTabPane.Attributes["class"] = LoginTabPane.Attributes["class"].Replace("active", "");

            if (!CreateTabPane.Attributes["class"].Contains("active"))
            {
                CreateTabPane.Attributes["class"] = CreateTabPane.Attributes["class"].Replace("fade", "") + " active in";
            }

            if (CreatePassword.Text != CreateConfirmPassword.Text)
            {
                TurnOnError("The confirmation password did not match the original password.",createerroralert,createAlertText);
                return;
            }

            if (_bl.GetUserByEmail(CreateEmail.Text) != null)
            {
                TurnOnError("The email " + CreateEmail.Text + " already exists in our database.", createerroralert, createAlertText);
                return;
            }

            User user = new User();
            user.Email = CreateEmail.Text;
            user.FirstName = CreateFirstName.Text;
            user.LastName = CreateLastName.Text;
            user.Password = CreatePassword.Text;
            user.Activated = false;
            user.Role = Role.User;
            var report = _bl.CreateUser(user);
            if (report.Valid)
            {
                createerroralert.Attributes["class"] = createerroralert.Attributes["class"].Replace("alert-error", "alert-success");
                createerroralert.Style["display"] = "block";
                createAlertText.InnerHtml = "Congratulations! An activation email was sent to " + user.Email + ".<br/>Click on the link and start enjoying YorKin Events!";
            }
            else
            {
                TurnOnError(report.Message, createerroralert, createAlertText);
                return;
            }
        }
        #endregion
        
        #region Private Methods
        private void TurnOnError(string errorMessage,HtmlGenericControl erroralert, HtmlGenericControl alertText)
        {
            erroralert.Attributes["class"] = erroralert.Attributes["class"].Replace("alert-success", "alert-error");
            erroralert.Style["display"] = "block";
            alertText.InnerHtml = errorMessage;
        }
        #endregion

        #region Page Methods
        [WebMethod]
        public static string SendPasswordRecoveryEmail(string email)
        {
            var json = new JavaScriptSerializer();
            Dictionary<string,object> responseDict = new Dictionary<string,object>();
            IBL bl = BusinessLayerFactory.GetCurrentBusinessLayer("");
            User user = bl.GetUserByEmail(email);
            if (user == null)
            {
                responseDict["STATUS"] = "FAILURE";
                responseDict["REASON"] = "NO_SUCH_EMAIL";
                responseDict["MESSAGE"] = "The email was not found in the database.";
                return json.Serialize(responseDict);
            }
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("r.n.lipkin@gmail.com", user.Email);
            message.IsBodyHtml = true;
            message.Body = @"
            Hi " + user.FirstName + @"! tsk tsk tsk... you lost your password. <b>NOT OKAY!</b>
            <br/>
            Pleeease try to keep your password safe!
            <br/>            
            <br/><br/><br/>
            YorKin Events
            <br/><br/><br/><br/><br/><br/>
            P.S. oh, and by the way, your password is <i>" + user.Password + @"</i>.
            ";
            message.Subject = "Password Recovery";
            try
            {
                bl.SendMail(message);
                responseDict["STATUS"] = "SUCCESS";
            }
            catch (Exception)
            {
                responseDict["STATUS"] = "FAILURE";
                responseDict["REASON"] = "NETWORK_ISSUE";
                responseDict["MESSAGE"] = "Our servers are experiancing some issues, try again later...";
            }
            return json.Serialize(responseDict);
        }
        #endregion
    }
}